import { getLocal, setLocal } from '@/utils/storage'
import { create } from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'

interface ChainData {
  chainName: string
  id: number
  leaderUserId: number
  chainServiceModeType: number // 上链服务模式 0 授权，1 申请
  joinFlag: boolean // 当前用户是否加入链
}

interface State {
  chain?: ChainData
  chainList?: ChainData[]
  refreshFlag: number
}

interface Action {
  setChain: (chain: ChainData) => void
  setChainList: (chainList: ChainData[]) => void
  refresh: () => void
}

const LocalKey = 'chain'

const initialState: State = {
  chain: getLocal<ChainData>(LocalKey) || undefined,
  refreshFlag: 0
}

const useChainStore = create<State & Action>()(
  subscribeWithSelector((set, get) => ({
    ...initialState,
    setChain: chain => {
      setLocal(LocalKey, chain)
      set({ chain })
    },
    setChainList: chainList => {
      set({ chainList })
    },
    refresh: () => {
      set({ refreshFlag: get().refreshFlag + 1 })
    }
  }))
)

export function getChain() {
  return useChainStore.getState().chain
}

export default useChainStore
